//
//  LMESchemeModel.m
//  WelfareManager
//
//  Created by longmin on 17/2/28.
//  Copyright © 2017年 timtian. All rights reserved.
//

#import "LMESchemeModel.h"
#import "LMESchemePageModel.h"

@implementation LMESchemeModel

#pragma mark - Public

- (void)insertPage:(LMESchemePageModel *)page AtIndex:(NSInteger)index {
    
    [self.page_list insertObject:page atIndex:index];
    
    NSInteger sortIndex = 1;
    for (LMESchemePageModel *pageModel in self.page_list) {
        pageModel.sort = sortIndex++;
    }
    
}

- (void)removePageAtIndex:(NSInteger)index {
    
    [self.page_list removeObjectAtIndex:index];
    
    NSInteger sortIndex = 1;
    for (LMESchemePageModel *pageModel in self.page_list) {
        pageModel.sort = sortIndex++;
    }
    
}

- (void)sortGoods {
    NSMutableArray <LMESchemePageModel *>*pageList = [NSMutableArray arrayWithArray:self.page_list];
    
    BOOL hasIntroduce = pageList[1].type == LMEPageTypeIntroduce;
    for (LMESchemePageModel *pageModel in pageList) {
        
        if (hasIntroduce && pageModel.type == LMEPageTypeGoods) {
            pageModel.sort += 2;
        }else if (!hasIntroduce && pageModel.type == LMEPageTypeGoods) {
            pageModel.sort++;
        }
    }
    
    [pageList sortUsingComparator:^NSComparisonResult(LMESchemePageModel *page1, LMESchemePageModel *page2) {
        
        return page1.sort > page2.sort;
    }];
    
    self.page_list = pageList;
}

- (NSMutableArray *)goodsList {
    
    NSMutableArray *goodsList = [NSMutableArray array];
    for (LMESchemePageModel *pageModel in self.page_list) {
        if (pageModel.type == LMEPageTypeGoods) {
            [goodsList addObject:pageModel];
        }
    }
    
    return goodsList;
}

- (void)addPageWithGoods:(LMEGoodsModel *)goods {
    NSMutableArray <LMESchemePageModel *> *pageList = [NSMutableArray arrayWithArray:self.page_list];
    LMESchemePageModel *pageModel = [[LMESchemePageModel alloc] initWithGoods:goods];
    pageModel.sort = pageList.count;
    [pageList lastObject].sort = pageList.count + 1;
    [pageList insertObject:pageModel atIndex:pageList.count - 1];
    
    self.page_list = pageList;
}

- (void)addPageWithGoodsList:(NSArray <LMEGoodsModel *> *)goodsList {
    
    for (LMEGoodsModel *goods in goodsList) {
        [self addPageWithGoods:goods];
    }
}

#pragma mark - MJExtention
+ (NSDictionary *)mj_objectClassInArray {
    return @{@"page_list" : [LMESchemePageModel class]};
}

#pragma mark - NSObject
- (NSString *)description {
    return [self mj_JSONString];
}

@end
